# -*- coding: utf-8 -*-
import random
import requests


API_KEY = '你的百度APIKEY'
headers = {'apikey': API_KEY}

def get_ip():
    ip = raw_input('输入查询IP：')
    url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup?ip=' + ip
    resp = requests.get(url, headers=headers)  # 调用时需将 apikey 放在 headers 里
    data = resp.json()  # json()方法可将json格式的结果直接转为字典对象
    data_ip = data.get('retData')
    if data.get('errNum') == 0:
        print data_ip['country'], data_ip['province'], data_ip['city'], data_ip['district'], data_ip['carrier']
    else:
        print data

def get_stock():
    stock = raw_input('输入股票代码（如 sh600001, sz000001）：')
    url = 'http://apis.baidu.com/apistore/stockservice/stock?list=0&stockid=' + stock
    resp = requests.get(url, headers=headers)
    data = resp.json()
    if data.get('errNum') == 0:
        data_stock = data['retData']['stockinfo']
        if data_stock['name'] != 'FAILED':
            print data_stock['name'], data_stock['currentPrice'], 
            percent = (data_stock['currentPrice'] - data_stock['closingPrice']) / data_stock['closingPrice'] * 100
            print '%.2f%%' % percent
        else:
            print '无效的股票代码'
    else:
        print data

def get_joke():
    page = random.randint(1, 100)
    url = 'http://apis.baidu.com/showapi_open_bus/showapi_joke/joke_text?page=%d' % page
    resp = requests.get(url, headers=headers)
    data = resp.json()
    index = random.randint(0, 19)
    if data.get('errNum') == 0:
        text = data['showapi_res_body']['contentlist'][index]['text']
        text = text.replace('</p>', '\n').replace('<p>', '').replace('<br />', '')
        print text
    else:
        print data

    
while True:
    choice = raw_input('1.查IP 2.查股票 3.讲个笑话 (回车退出)\n')
    if choice == '1':
        get_ip()
    elif choice == '2':
        get_stock()
    elif choice == '3':
        get_joke()
    elif choice == '':
        break
    print
